//
//  ImageSelectViewController.m
//  ImageWorkshop
//
//  Created by Runli Song on 2023/11/23.
//  Copyright © 2023 James Song. All rights reserved.
//

#import "ImageSelectViewController.h"
#import "ImageProcessViewController.h"
#import "SWImageTransferViewController.h"
#import "Text2ImageViewController.h"
#import "BaseNavigationController.h"

@interface ImageSelectViewController () <UIImagePickerControllerDelegate,UINavigationControllerDelegate, UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) UIButton *mainImageView;
@property (nonatomic, strong) UIButton *selectImageBtn;
@property (nonatomic, strong) UIButton *downloadImageBtn;


@property (nonatomic, strong) UICollectionView *functionsCollection;
@property (nonatomic, copy) NSArray *featureList;

@end

@implementation ImageSelectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setRightItemWithTitle:@"进入画布" selector:@selector(onClickRight) color:MainThemeColor];
    [self.view addSubview:self.functionsCollection];
    [self.functionsCollection mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.equalTo(@(-20));
        make.left.equalTo(@(20));
        make.height.equalTo(@(50));
    }];
    [self.functionsCollection reloadData];
    
    [self.view addSubview:self.selectImageBtn];
    [_selectImageBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.functionsCollection);
        make.bottom.equalTo(self.functionsCollection.mas_top).offset(-20);
        make.width.equalTo(@(kScreenWidth/2 - 30));
        make.height.equalTo(@(50));
    }];
    
    [self.view addSubview:self.downloadImageBtn];
    [self.downloadImageBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.width.equalTo(self.selectImageBtn);
        make.left.equalTo(self.selectImageBtn.mas_right).offset(20);
    }];
    
    [self.view addSubview: self.mainImageView];
    [self.mainImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(@(20));
        make.right.equalTo(@(-20));
        make.bottom.equalTo(self.selectImageBtn.mas_top).offset(-20);
    }];
}

-(void)onClickRight{
    Text2ImageViewController * vc = [[Text2ImageViewController alloc]init];
    [vc setImage:_mainImageView.imageView.image];
    [self.navigationController pushViewController:vc animated:YES];

}

-(void)onClickSelectImage:(UIButton *)btn
{
    UIImagePickerController * picker = [[UIImagePickerController alloc]init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)onClickDownload{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"下载图片" message:@"请输入图片链接" preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"例：http://somePic.jpg";
        textField.font = [UIFont systemFontOfSize:14];
        textField.textColor = UIColor.blackColor;
    }];
    
    UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [alert dismissViewControllerAnimated:YES completion:nil];
    }];
    [alert addAction:cancel];
    
    UIAlertAction *done = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (alert.textFields.count > 0) {
            NSString *imageUrl = alert.textFields[0].text;
            if (imageUrl) {
                if ([imageUrl containsString:@"http://"] || [imageUrl containsString:@"https://"]) {
                    [self downloadImageWithURL:imageUrl];
                }else{
                    [SVProgressHUD showErrorWithStatus:@"请输入有效的链接"];
                }
            }
        }
    }];
    
    [alert addAction:done];
    
    [self presentViewController:alert animated:YES completion:nil];
}

-(void)downloadImageWithURL:(NSString *)imageUrl{
    [SVProgressHUD show];
    [self.mainImageView sd_setImageWithURL:[NSURL URLWithString:imageUrl] forState:UIControlStateNormal completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        [SVProgressHUD dismiss];
    }];
}

#pragma mark - UIImagePickerControllerDelegate

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage * image = info[@"UIImagePickerControllerOriginalImage"];
    
    [_mainImageView setImage:image forState:UIControlStateNormal];
    
}

#pragma mark UICollectionViewDataSource/UICollectionViewDelegate
//定义展示的UICollectionViewCell的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.featureList.count;
}

//每个UICollectionView展示的内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString * CellIdentifier = @"CollectionViewCell";
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    cell.contentView.backgroundColor = MainThemeColor;
    cell.contentView.layer.cornerRadius = 10;
    UILabel * title = [[UILabel alloc] init];
    title.text = self.featureList[indexPath.item];
    title.font = [UIFont systemFontOfSize:14];
    title.textColor = UIColor.whiteColor;
    title.textAlignment = NSTextAlignmentCenter;
    [cell.contentView addSubview:title];
    [title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(cell.contentView);
    }];
    return cell;
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((kScreenWidth - 40)/5 - 10, 50);
}

//UICollectionView被选中时调用的方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (!_mainImageView.imageView.image) {
        [SVProgressHUD showErrorWithStatus:@"请先选择图片"];
        return;
    }
    
    ImageProcessViewController * vc = [[ImageProcessViewController alloc] init];
    [vc setImage:_mainImageView.imageView.image];
    [vc setActionType:indexPath.item];
    [self presentViewController:vc animated:YES completion:nil];
}


#pragma mark - getter

- (UIButton *)mainImageView{
    if(!_mainImageView){
        _mainImageView = [UIButton buttonWithType:UIButtonTypeCustom];
        _mainImageView.contentMode = UIViewContentModeScaleAspectFit;
        _mainImageView.imageView.contentMode = UIViewContentModeScaleAspectFit;
        _mainImageView.backgroundColor = UIColorFromHex(0xf0f0f0);
        [_mainImageView setTitle:@"请选择图片" forState:UIControlStateNormal];
        [_mainImageView setTitleColor:MainThemeColor forState:UIControlStateNormal];
    }
    return _mainImageView;
}

- (UIButton *)selectImageBtn{
    if(!_selectImageBtn){
        _selectImageBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [_selectImageBtn setTitle:@"本地选择图片" forState:UIControlStateNormal];
        [_selectImageBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        _selectImageBtn.layer.cornerRadius = 10;
        _selectImageBtn.layer.masksToBounds = YES;
        _selectImageBtn.backgroundColor = MainThemeColor;
        [_selectImageBtn addTarget:self action:@selector(onClickSelectImage:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _selectImageBtn;
}

- (UIButton *)downloadImageBtn{
    if(!_downloadImageBtn){
        _downloadImageBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_downloadImageBtn setTitle:@"下载图片" forState:UIControlStateNormal];
        [_downloadImageBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        _downloadImageBtn.layer.cornerRadius = 10;
        _downloadImageBtn.layer.masksToBounds = YES;
        _downloadImageBtn.backgroundColor = MainThemeColor;
        [_downloadImageBtn addTarget:self action:@selector(onClickDownload) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _downloadImageBtn;
}

- (UICollectionView *)functionsCollection{
    if(!_functionsCollection){
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumLineSpacing = 10;
        layout.minimumInteritemSpacing = 10;
        _functionsCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(_mainImageView.frameOriginX, _selectImageBtn.frameMaxY + 20, 300, 100) collectionViewLayout:layout];
        _functionsCollection.backgroundColor = [UIColor clearColor];
        _functionsCollection.delegate = self;
        _functionsCollection.dataSource = self;
        [_functionsCollection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"CollectionViewCell"];
    }
    return _functionsCollection;
}

- (NSArray *)featureList{
    if(!_featureList){
        _featureList = @[
            @"加水印",
            @"加阴影",
            @"旋转",
            @"裁剪",
            @"切圆角"
        ];
    }
    return _featureList;
}


@end
